// 投注管理文件 - 包含投注相关的所有功能

import { STATE, StateManager } from './state.js';
import { CommonUtils, TailUtils } from './utils.js';
import { UIManager } from './ui.js';
import { animalConfig, oddsConfig, tailConfig } from './config.js';

// 投注管理器
export const BettingManager = {
    // 处理号码点击
    handleNumberClick(button) {
        const number = parseInt(button.getAttribute('data-number'));
        const isSelected = button.classList.contains('selected');
        
        if (isSelected) {
            // 取消选择
            button.classList.remove('selected');
            StateManager.removeSelectedNumber(number);
        } else {
            // 选择号码
            button.classList.add('selected');
            StateManager.addSelectedNumber(number);
        }
        
        this.updateSelectionInfo();
    },

    // 更新选择信息
    updateSelectionInfo() {
        const count = STATE.selectedNumbers.size;
        let displayCount = count;
        
        // 对于连码玩法，显示组合注数
        if (STATE.currentGame === 'lianma' && count > 0) {
            const numbers = Array.from(STATE.selectedNumbers);
            displayCount = CommonUtils.calculateLianmaCount(numbers, STATE.currentSub);
        }
        // 对于不中玩法，显示组合注数
        else if (STATE.currentGame === 'buzhong' && count > 0) {
            const numbers = Array.from(STATE.selectedNumbers);
            displayCount = this.calculateBuzhongCombinationCount(numbers, STATE.currentSub);
        }
        
        const panelKey = `${STATE.currentGame}-${STATE.currentSub}`;
        UIManager.updateSelectionInfo(panelKey, displayCount);
    },

    // 处理两面投注按钮点击
    handleSideButtonClick(button) {
        const betType = button.getAttribute('data-bet');
        const odds = parseFloat(button.getAttribute('data-odds'));
        const position = button.getAttribute('data-position') || 'tema';
        const isSelected = button.classList.contains('selected');
        
        // 获取按钮文本（去掉赔率部分）
        const buttonText = button.textContent.split('\n')[0] || button.textContent.split('赔率')[0];
        const betName = buttonText.trim();
        
        const gameType = STATE.currentGame === 'tema' ? '特码' : '正码';
        let subType = '特码两面';
        if (position === 'tema') {
            subType = '特码两面';
        } else if (position === '1') {
            subType = '正码1两面';
        } else if (position === '2') {
            subType = '正码2两面';
        } else if (position === '3') {
            subType = '正码3两面';
        } else if (position === '4') {
            subType = '正码4两面';
        } else if (position === '5') {
            subType = '正码5两面';
        } else if (position === '6') {
            subType = '正码6两面';
        } else {
            subType = `正码${position}两面`;
        }
        const description = `[${gameType},${subType}]${betName}`;
        
        if (isSelected) {
            // 取消选中状态
            button.classList.remove('selected');
            
            // 从投注清单中移除对应项目
            STATE.betList = STATE.betList.filter(bet => {
                return !(bet.type === 'sides' && 
                        bet.game === STATE.currentGame && 
                        bet.sub === STATE.currentSub && 
                        bet.sideType === betType && 
                        bet.position === position);
            });
        } else {
            // 设置选中状态
            button.classList.add('selected');
            
            // 获取玩法标识（两面投注使用更精确的标识）
            const gameTypeKey = CommonUtils.getSidesBetGameTypeKey(STATE.currentGame, STATE.currentSub, betType, position);
            
            // 优先使用历史赔率，否则使用按钮上的赔率
            const lastUsedOdds = StateManager.getLastUsedOdds(gameTypeKey);
            const initialOdds = lastUsedOdds || odds;
            
            // 添加到投注清单
            const betItem = {
                id: CommonUtils.generateId(),
                type: 'sides',
                game: STATE.currentGame,
                sub: STATE.currentSub,
                sideType: betType,
                position: position,
                count: 1,
                amount: 10,
                odds: initialOdds,
                gameTypeKey: gameTypeKey,
                description: description
            };
            
            StateManager.addBetItem(betItem);
        }
        
        // 更新投注清单显示
        this.updateBettingListDisplay();
        
        // 添加视觉反馈
        button.style.transform = 'scale(0.95)';
        setTimeout(() => {
            button.style.transform = 'scale(1)';
        }, 150);
    },

    // 处理半波按钮点击
    handleBanboButtonClick(button) {
        const banboType = button.getAttribute('data-banbo');
        const odds = parseFloat(button.getAttribute('data-odds'));
        const isSelected = button.classList.contains('selected');
        
        // 获取按钮文本（去掉赔率部分）
        const buttonText = button.textContent.split('\n')[0] || button.textContent.split('赔率')[0];
        const betName = buttonText.trim();
        
        const description = `[半波,特码半波]${betName}`;
        
        if (isSelected) {
            // 取消选中状态
            button.classList.remove('selected');
            
            // 从投注清单中移除对应项目
            STATE.betList = STATE.betList.filter(bet => {
                return !(bet.type === 'banbo' && 
                        bet.game === STATE.currentGame && 
                        bet.sub === STATE.currentSub && 
                        bet.banbo === banboType);
            });
        } else {
            // 设置选中状态
            button.classList.add('selected');
            
            // 获取玩法标识
            const gameTypeKey = `banbo_${banboType}`;
            
            // 优先使用历史赔率，否则使用按钮上的赔率
            const lastUsedOdds = StateManager.getLastUsedOdds(gameTypeKey);
            const initialOdds = lastUsedOdds || odds;
            
            // 添加到投注清单
            const betItem = {
                id: CommonUtils.generateId(),
                type: 'banbo',
                game: STATE.currentGame,
                sub: STATE.currentSub,
                banbo: banboType,
                count: 1,
                amount: 10,
                odds: initialOdds,
                gameTypeKey: gameTypeKey,
                description: description
            };
            
            StateManager.addBetItem(betItem);
        }
        
        // 更新投注清单显示
        this.updateBettingListDisplay();
        
        // 添加视觉反馈
        button.style.transform = 'scale(0.95)';
        setTimeout(() => {
            button.style.transform = 'scale(1)';
        }, 150);
    },

    // 确认半波选择
    confirmBanboSelection() {
        const selectedButtons = document.querySelectorAll('.banbo-btn-detailed.selected');
        if (selectedButtons.length === 0) return;
        
        // 半波按钮点击时已经添加到投注清单，这里只需要更新选择信息
        this.updateBanboSelectionInfo();
    },

    // 更新半波选择信息
    updateBanboSelectionInfo() {
        const selectedButtons = document.querySelectorAll('.banbo-btn-detailed.selected');
        const count = selectedButtons.length;
        
        const selectionCount = document.getElementById('banboSelectionCount');
        const confirmBtn = document.getElementById('banboConfirmBtn');
        
        if (selectionCount) {
            selectionCount.textContent = `您选择了 ${count} 注`;
        }
        
        if (confirmBtn) {
            confirmBtn.disabled = count === 0;
        }
    },

    // 确认号码选择
    confirmNumberSelection() {
        if (STATE.selectedNumbers.size === 0) return;
        
        const numbers = Array.from(STATE.selectedNumbers).sort((a, b) => a - b);
        const gameType = STATE.currentGame === 'tema' ? '特码' : 
                        STATE.currentGame === 'lianma' ? '连码' : '正码';
        
        let subType = '其他';
        let count = numbers.length;
        
        // 处理连码玩法
        if (STATE.currentGame === 'lianma') {
            switch (STATE.currentSub) {
                case 'sanquanzhong':
                    subType = '连码三全中';
                    count = CommonUtils.calculateLianmaCount(numbers, STATE.currentSub);
                    break;
                case 'sanzhonger':
                    subType = '连码三中二';
                    count = CommonUtils.calculateLianmaCount(numbers, STATE.currentSub);
                    break;
                case 'erquanzhong':
                    subType = '连码二全中';
                    count = CommonUtils.calculateLianmaCount(numbers, STATE.currentSub);
                    break;
                case 'erzhongte':
                    subType = '连码二中特';
                    count = CommonUtils.calculateLianmaCount(numbers, STATE.currentSub);
                    break;
                case 'techuan':
                    subType = '连码特串';
                    count = CommonUtils.calculateLianmaCount(numbers, STATE.currentSub);
                    break;
            }
        } else {
            // 处理其他玩法
            if (STATE.currentSub === 'zhixuan') {
                subType = '特码直选';
            } else if (STATE.currentSub === 'renxuan') {
                subType = '正码任选';
            } else if (STATE.currentSub === 'zheng1te') {
                subType = '正码1特';
            } else if (STATE.currentSub === 'zheng2te') {
                subType = '正码2特';
            } else if (STATE.currentSub === 'zheng3te') {
                subType = '正码3特';
            } else if (STATE.currentSub === 'zheng4te') {
                subType = '正码4特';
            } else if (STATE.currentSub === 'zheng5te') {
                subType = '正码5特';
            } else if (STATE.currentSub === 'zheng6te') {
                subType = '正码6特';
            }
        }
        
        // 获取玩法标识
        const gameTypeKey = CommonUtils.getGameTypeKey(STATE.currentGame, STATE.currentSub);
        
        // 获取赔率
        let initialOdds;
        if (STATE.currentGame === 'lianma') {
            initialOdds = CommonUtils.getLianmaOdds(STATE.currentSub);
        } else {
            // 优先使用历史赔率，否则使用默认赔率
            const lastUsedOdds = StateManager.getLastUsedOdds(gameTypeKey);
            const defaultOdds = CommonUtils.getCurrentOdds();
            initialOdds = lastUsedOdds || defaultOdds;
        }
        
        // 检查连码最小选号要求
        if (STATE.currentGame === 'lianma') {
            const minRequired = (STATE.currentSub === 'sanquanzhong' || STATE.currentSub === 'sanzhonger') ? 3 : 2;
            if (numbers.length < minRequired) {
                alert(`${subType}至少需要选择${minRequired}个号码`);
                return;
            }
            if (count === 0) {
                alert('选择的号码数量不足以组成有效投注');
                return;
            }
        }
        
        const betItem = {
            id: CommonUtils.generateId(),
            type: 'numbers',
            game: STATE.currentGame,
            sub: STATE.currentSub,
            numbers: numbers,
            count: count,
            amount: 10,
            odds: initialOdds,
            gameTypeKey: gameTypeKey,
            description: `[${gameType},${subType}] ${numbers.map(n => n.toString().padStart(2, '0')).join(',')}`
        };
        
        StateManager.addBetItem(betItem);
        
        // 清空选择
        this.clearNumberSelection();
        
        // 更新投注清单显示
        this.updateBettingListDisplay();
    },

    // 清空号码选择
    clearNumberSelection() {
        StateManager.clearSelectedNumbers();
        document.querySelectorAll('.number-btn.selected').forEach(btn => {
            btn.classList.remove('selected');
        });
        this.updateSelectionInfo();
    },

    // 删除投注项目
    deleteBetItem(deleteBtn) {
        console.log('deleteBetItem被调用，删除按钮:', deleteBtn);
        
        const betItem = deleteBtn.closest('.bet-item');
        const betId = betItem.getAttribute('data-bet-id');
        
        // 找到投注项目
        
        // 找到要删除的投注项目 - 使用严格的字符串比较
        const betToDelete = STATE.betList.find(bet => String(bet.id) === String(betId));
        // 准备删除投注项目
        
        // 如果是两面投注，需要取消对应按钮的选中状态
        if (betToDelete && betToDelete.type === 'sides') {
            let selector;
            if (betToDelete.position === 'tema') {
                // 特码两面：只匹配data-bet，不匹配data-position
                selector = `[data-bet="${betToDelete.sideType}"]:not([data-position])`;
            } else {
                // 正码两面：匹配data-bet和data-position
                selector = `[data-bet="${betToDelete.sideType}"][data-position="${betToDelete.position}"]`;
            }
            
            const button = document.querySelector(selector);
            if (button) {
                button.classList.remove('selected');
                console.log('已取消按钮选中状态');
            } else {
                console.log('未找到对应的按钮');
            }
        }
        
        // 如果是半波投注，需要取消对应按钮的选中状态
        if (betToDelete && betToDelete.type === 'banbo') {
            const selector = `[data-banbo="${betToDelete.banbo}"]`;
            const button = document.querySelector(selector);
            if (button) {
                button.classList.remove('selected');
                console.log('已取消半波按钮选中状态');
            } else {
                console.log('未找到对应的半波按钮');
            }
        }
        
        // 从投注清单中移除
        StateManager.removeBetItem(betId);
        // 已从STATE中移除投注项目
        
        // 更新显示
        this.updateBettingListDisplay();
        // 已更新投注清单显示
    },

    // 只更新投注汇总信息，不重新渲染整个清单
    updateBettingSummary() {
        const totalBetsSpan = document.getElementById('totalBets');
        const totalAmountSpan = document.getElementById('totalAmount');
        const submitBtn = document.getElementById('submitBetBtn');
        
        // 更新汇总信息
        const totalBets = STATE.betList.reduce((sum, bet) => sum + bet.count, 0);
        const totalAmount = STATE.betList.reduce((sum, bet) => sum + (bet.amount * bet.count), 0);
        
        if (totalBetsSpan) totalBetsSpan.textContent = totalBets;
        if (totalAmountSpan) totalAmountSpan.textContent = totalAmount;
        
        // 更新立即投注按钮状态
        if (submitBtn) {
            if (STATE.betList.length > 0) {
                submitBtn.disabled = false;
                submitBtn.textContent = '立即投注';
            } else {
                submitBtn.disabled = true;
                submitBtn.textContent = '立即投注';
            }
        }
    },

    // 更新投注清单显示
    updateBettingListDisplay() {
        const betItems = document.getElementById('betItems');
        const totalBetsSpan = document.getElementById('totalBets');
        const totalAmountSpan = document.getElementById('totalAmount');
        const submitBtn = document.getElementById('submitBetBtn');
        
        if (!betItems) return;
        
        // 清空现有内容
        betItems.innerHTML = '';
        
        if (STATE.betList.length === 0) {
            betItems.innerHTML = '<div style="text-align: center; color: #6c757d; padding: 20px;">暂无投注项目</div>';
        } else {
            STATE.betList.forEach(bet => {
                const betElement = UIManager.createBetItemElement(bet);
                betItems.appendChild(betElement);
            });
        }
        
        // 更新汇总信息
        const totalBets = STATE.betList.reduce((sum, bet) => sum + bet.count, 0);
        const totalAmount = STATE.betList.reduce((sum, bet) => sum + (bet.amount * bet.count), 0);
        
        if (totalBetsSpan) totalBetsSpan.textContent = totalBets;
        if (totalAmountSpan) totalAmountSpan.textContent = totalAmount;
        
        // 更新立即投注按钮状态
        if (submitBtn) {
            if (STATE.betList.length > 0) {
                submitBtn.disabled = false;
                submitBtn.textContent = '立即投注';
            } else {
                submitBtn.disabled = true;
                submitBtn.textContent = '立即投注';
            }
        }
    },

    // 强制刷新所有投注项的可中金额显示
    refreshAllPotentialWins() {
            // 开始刷新所有投注项的潜在赔付
        
        document.querySelectorAll('.bet-item').forEach(betItem => {
            const betId = betItem.getAttribute('data-bet-id');
            const bet = STATE.betList.find(b => String(b.id) === String(betId));
            
            console.log('处理投注项:', { betId, bet });
            
            if (bet) {
                console.log('投注详情:', {
                    type: bet.type,
                    game: bet.game,
                    sub: bet.sub,
                    count: bet.count,
                    amount: bet.amount,
                    odds: bet.odds || bet.customOdds
                });
                
                // 检查是否符合特码直选多选条件
                const isTemasDirectMultiple = window.PayoutCalculator.isTemasDirectMultiple(bet);
                console.log('是否为特码直选多选:', isTemasDirectMultiple);
                
                const potentialAmount = betItem.querySelector('.potential-amount');
                const potentialLabel = betItem.querySelector('.bet-potential span');
                
                if (potentialAmount) {
                    // 直接测试计算逻辑
                    // 直接测试计算逻辑
                    console.log('bet.amount:', bet.amount);
                    console.log('bet.count:', bet.count);
                    console.log('bet.odds:', bet.odds);
                    console.log('bet.customOdds:', bet.customOdds);
                    
                    // 强制使用统一的赔付计算器
                    const potentialWin = window.PayoutCalculator.calculatePotentialPayout(bet);
                    
                    console.log('统一计算器结果:', potentialWin);
                    potentialAmount.textContent = `${potentialWin.toFixed(2)}元`;
                }
                
                if (potentialLabel) {
                    const labelText = window.PayoutCalculator.getPotentialPayoutLabel(bet);
                    const potentialWin = window.PayoutCalculator.calculatePotentialPayout(bet);
                    console.log('设置标签文本:', labelText);
                    potentialLabel.innerHTML = `${labelText}：<span class="potential-amount">${potentialWin.toFixed(2)}元</span>`;
                }
            }
        });
        
        // 刷新完成
    },

    // 更新投注金额
    updateBetAmount(input) {
        const betItem = input.closest('.bet-item');
        const betId = betItem.getAttribute('data-bet-id');
        const newAmount = parseFloat(input.value) || 10;
        
        // 更新STATE中的数据 - 使用严格的字符串比较
        const bet = STATE.betList.find(b => String(b.id) === String(betId));
        if (bet) {
            bet.amount = newAmount;
            
            // 更新可中金额显示
            const potentialAmount = betItem.querySelector('.potential-amount');
            if (potentialAmount) {
                const potentialWin = window.PayoutCalculator.calculatePotentialPayout(bet);
                potentialAmount.textContent = `${potentialWin.toFixed(2)}元`;
            }
        }
        
        this.updateBettingSummary();
    },

    // 更新投注赔率
    updateBetOdds(input) {
        const betItem = input.closest('.bet-item');
        const betId = betItem.getAttribute('data-bet-id');
        const newOdds = parseFloat(input.value) || 1;
        
        // 更新STATE中的数据 - 使用严格的字符串比较
        const bet = STATE.betList.find(b => String(b.id) === String(betId));
        if (bet) {
            bet.customOdds = newOdds;
            
            // 保存赔率到历史记录
            if (bet.gameTypeKey) {
                StateManager.saveOddsToHistory(bet.gameTypeKey, newOdds);
            }
            
            // 更新可中金额显示
            const potentialAmount = betItem.querySelector('.potential-amount');
            if (potentialAmount) {
                const potentialWin = window.PayoutCalculator.calculatePotentialPayout(bet);
                potentialAmount.textContent = `${potentialWin.toFixed(2)}元`;
            }
        }
        
        this.updateBettingSummary();
    },

    // 显示确认弹窗
    showConfirmModal() {
        // 显示确认弹窗
        
        if (STATE.betList.length === 0) {
            alert('请先选择投注项目');
            return;
        }
        
        const totalAmount = STATE.betList.reduce((sum, bet) => sum + (bet.amount * bet.count), 0);
        const modalData = {
            betList: STATE.betList,
            totalAmount: totalAmount
        };
        
        console.log('模态框数据:', modalData);
        UIManager.showModal('confirmModal', modalData);
    },

    // 隐藏确认弹窗
    hideConfirmModal() {
        UIManager.hideModal('confirmModal');
    },

    // 提交投注
    submitBets() {
        // 开始提交投注
        
        try {
            // 收集投注数据用于统计
            const totalAmount = STATE.betList.reduce((sum, bet) => sum + (bet.amount * bet.count), 0);
            console.log('计算总金额:', totalAmount);
            
            const gameTypes = [...new Set(STATE.betList.map(bet => {
                if (bet.game === 'tema') {
                    return bet.sub === 'zhixuan' ? '特码直选' : '特码两面';
                } else if (bet.game === 'zhengma') {
                    return '正码任选';
                }
                return '其他';
            }))];
            console.log('游戏类型:', gameTypes);
            
            const contents = STATE.betList.map(bet => {
                if (bet.type === 'numbers') {
                    return bet.numbers.map(n => n.toString().padStart(2, '0')).join(',');
                } else {
                    return bet.sideType;
                }
            });
            console.log('投注内容:', contents);
            
            const allNumbers = STATE.betList
                .filter(bet => bet.type === 'numbers')
                .flatMap(bet => bet.numbers);
            console.log('所有号码:', allNumbers);
            
            // 收集赔率信息
            const oddsInfo = STATE.betList.map(bet => {
                const odds = bet.customOdds || bet.odds || 1;
                return `${bet.description}:${odds}`;
            });
            
            // 添加到统计数据
            const betData = {
                game: STATE.currentGame,
                sub: STATE.currentSub,
                gameType: gameTypes.join(','),
                content: contents.join(';'),
                totalAmount: totalAmount,
                numbers: allNumbers.length > 0 ? allNumbers : null,
                odds: oddsInfo.join(';'),
                betDetails: STATE.betList.map(bet => ({
                    type: bet.type,
                    description: bet.description,
                    amount: bet.amount,
                    count: bet.count,
                    odds: bet.customOdds || bet.odds || 1,
                    potentialWin: window.PayoutCalculator.calculatePotentialPayout(bet)
                }))
            };
            // 投注数据准备完成
            
            // 将投注数据添加到坐庄系统
            STATE.betList.forEach(bet => {
                // 为坐庄系统准备投注数据
                const bankerBetData = {
                    type: bet.type,
                    game: STATE.currentGame,
                    sub: STATE.currentSub,
                    description: bet.description,
                    amount: bet.amount,
                    count: bet.count,
                    odds: bet.customOdds || bet.odds || 1,
                    numbers: bet.numbers || null,
                    sideType: bet.sideType || null,
                    position: bet.position || null,
                    banbo: bet.banbo || null,
                    banboType: bet.banboType || null,
                    selectedBanbos: bet.selectedBanbos || null,
                    animals: bet.animals || null,
                    tails: bet.tails || null,
                    heads: bet.heads || null,
                    sebo: bet.sebo || null
                };
                
                // 使用动态导入来避免循环依赖
                if (window.BankerManager) {
                    window.BankerManager.addBet(bankerBetData);
                }
            });
            
            // 这里可以添加实际的投注提交逻辑
            alert('投注提交成功！');
            
            // 清空投注清单
            StateManager.clearBetList();
            UIManager.clearAllSelections();
            this.updateBettingListDisplay();
            
            // 关闭弹窗
            this.hideConfirmModal();
            
            // 投注提交完成
        } catch (error) {
            console.error('投注提交过程中出错:', error);
            alert('投注提交失败: ' + error.message);
        }
    },

    // 处理生肖按钮点击
    handleAnimalClick(button) {
        const animalId = button.getAttribute('data-animal');
        const animal = animalConfig.getAnimalById(animalId);
        const isSelected = button.classList.contains('selected');
        
        if (!animal) return;
        
        if (isSelected) {
            // 取消选择
            button.classList.remove('selected');
            StateManager.removeSelectedAnimal(animalId);
        } else {
            // 检查选择限制
            if (!this.checkAnimalSelectionLimit(animalId)) {
                return;
            }
            
            // 选择生肖
            button.classList.add('selected');
            StateManager.addSelectedAnimal(animalId);
        }
        
        this.updateAnimalSelectionInfo();
    },

    // 检查生肖选择限制
    checkAnimalSelectionLimit(animalId) {
        const currentCount = STATE.selectedAnimals.size;
        const currentSub = STATE.currentSub;
        
        // 根据不同玩法设置选择限制
        let maxLimit = 12;
        let minLimit = 1;
        
        switch (currentSub) {
            case 'erxiaolian':
                minLimit = 2;
                break;
            case 'sanxiaolian':
                minLimit = 3;
                break;
            case 'sixiaolian':
                minLimit = 4;
                break;
            case 'hexiaozhong':
            case 'hexiaobuzhong':
                minLimit = 2;
                maxLimit = 10;
                break;
        }
        
        if (currentCount >= maxLimit) {
            alert(`最多只能选择${maxLimit}个生肖`);
            return false;
        }
        
        return true;
    },

    // 更新生肖选择信息
    updateAnimalSelectionInfo() {
        const count = STATE.selectedAnimals.size;
        let displayCount = count;
        
        // 对于连肖玩法，显示组合注数
        if (['erxiaolian', 'sanxiaolian', 'sixiaolian'].includes(STATE.currentSub) && count > 0) {
            const animals = Array.from(STATE.selectedAnimals);
            displayCount = this.calculateAnimalCombinationCount(animals, STATE.currentSub);
        }
        
        const panelKey = `${STATE.currentGame}-${STATE.currentSub}`;
        UIManager.updateSelectionInfo(panelKey, displayCount);
    },

    // 计算生肖组合注数
    calculateAnimalCombinationCount(animals, subType) {
        const count = animals.length;
        
        switch (subType) {
            case 'erxiaolian':
                return count >= 2 ? CommonUtils.combination(count, 2) : 0;
            case 'sanxiaolian':
                return count >= 3 ? CommonUtils.combination(count, 3) : 0;
            case 'sixiaolian':
                return count >= 4 ? CommonUtils.combination(count, 4) : 0;
            default:
                return count;
        }
    },

    // 处理总肖按钮点击
    handleZongxiaoButtonClick(button) {
        const zongxiaoType = button.getAttribute('data-zongxiao');
        const odds = parseFloat(button.getAttribute('data-odds'));
        const isSelected = button.classList.contains('selected');
        
        // 获取按钮文本
        const betName = button.querySelector('.zongxiao-name').textContent;
        const description = `[生肖,总肖]${betName}`;
        
        if (isSelected) {
            // 取消选中状态
            button.classList.remove('selected');
            
            // 从投注清单中移除对应项目
            STATE.betList = STATE.betList.filter(bet => {
                return !(bet.type === 'zongxiao' && 
                        bet.game === STATE.currentGame && 
                        bet.sub === STATE.currentSub && 
                        bet.zongxiaoType === zongxiaoType);
            });
        } else {
            // 设置选中状态
            button.classList.add('selected');
            
            // 获取玩法标识
            const gameTypeKey = `zongxiao_${zongxiaoType}`;
            
            // 优先使用历史赔率，否则使用按钮上的赔率
            const lastUsedOdds = StateManager.getLastUsedOdds(gameTypeKey);
            const initialOdds = lastUsedOdds || odds;
            
            // 添加到投注清单
            const betItem = {
                id: CommonUtils.generateId(),
                type: 'zongxiao',
                game: STATE.currentGame,
                sub: STATE.currentSub,
                zongxiaoType: zongxiaoType,
                count: 1,
                amount: 10,
                odds: initialOdds,
                gameTypeKey: gameTypeKey,
                description: description
            };
            
            StateManager.addBetItem(betItem);
        }
        
        // 更新投注清单显示
        this.updateBettingListDisplay();
        
        // 添加视觉反馈
        button.style.transform = 'scale(0.95)';
        setTimeout(() => {
            button.style.transform = 'scale(1)';
        }, 150);
    },

    // 确认生肖选择（用于需要确认的生肖玩法）
    confirmAnimalSelection() {
        const selectedAnimals = Array.from(STATE.selectedAnimals);
        const currentSub = STATE.currentSub;
        
        if (selectedAnimals.length === 0) {
            alert('请先选择生肖');
            return;
        }
        
        // 验证选择数量
        if (!this.validateAnimalSelection(selectedAnimals, currentSub)) {
            return;
        }
        
        // 根据不同玩法生成投注项
        this.generateAnimalBetItems(selectedAnimals, currentSub);
        
        // 清空选择状态
        UIManager.clearAnimalSelections();
        StateManager.clearSelectedAnimals();
        this.updateAnimalSelectionInfo();
        
        // 更新投注清单显示
        this.updateBettingListDisplay();
    },

    // 验证生肖选择
    validateAnimalSelection(selectedAnimals, subType) {
        const count = selectedAnimals.length;
        
        switch (subType) {
            case 'erxiaolian':
                if (count < 2) {
                    alert('二肖连至少需要选择2个生肖');
                    return false;
                }
                break;
            case 'sanxiaolian':
                if (count < 3) {
                    alert('三肖连至少需要选择3个生肖');
                    return false;
                }
                break;
            case 'sixiaolian':
                if (count < 4) {
                    alert('四肖连至少需要选择4个生肖');
                    return false;
                }
                break;
            case 'hexiaozhong':
            case 'hexiaobuzhong':
                if (count < 2 || count > 10) {
                    alert('合肖玩法需要选择2-10个生肖');
                    return false;
                }
                break;
        }
        
        return true;
    },

    // 生成生肖投注项
    generateAnimalBetItems(selectedAnimals, subType) {
        const gameTypeKey = `shengxiao_${subType}`;
        const lastUsedOdds = StateManager.getLastUsedOdds(gameTypeKey);
        
        switch (subType) {
            case 'texiao':
            case 'yixiao':
            case 'zhengxiao':
                // 单个生肖投注
                selectedAnimals.forEach(animalId => {
                    const animal = animalConfig.getAnimalById(animalId);
                    const odds = this.getAnimalOdds(animal, subType);
                    const initialOdds = lastUsedOdds || odds;
                    
                    const betItem = {
                        id: CommonUtils.generateId(),
                        type: 'animal',
                        game: STATE.currentGame,
                        sub: STATE.currentSub,
                        animals: [animalId],
                        count: 1,
                        amount: 10,
                        odds: initialOdds,
                        gameTypeKey: gameTypeKey,
                        description: `[生肖,${this.getSubTypeName(subType)}]${animal.name}`
                    };
                    
                    StateManager.addBetItem(betItem);
                });
                break;
                
            case 'erxiaolian':
                // 二肖连组合投注
                this.generateAnimalCombinations(selectedAnimals, 2, subType, gameTypeKey, lastUsedOdds);
                break;
                
            case 'sanxiaolian':
                // 三肖连组合投注
                this.generateAnimalCombinations(selectedAnimals, 3, subType, gameTypeKey, lastUsedOdds);
                break;
                
            case 'sixiaolian':
                // 四肖连组合投注
                this.generateAnimalCombinations(selectedAnimals, 4, subType, gameTypeKey, lastUsedOdds);
                break;
                
            case 'hexiaozhong':
            case 'hexiaobuzhong':
                // 合肖投注
                const odds = oddsConfig.shengxiao[subType][selectedAnimals.length];
                const initialOdds = lastUsedOdds || odds;
                
                const animalNames = selectedAnimals.map(id => animalConfig.getAnimalById(id).name);
                let description = `[生肖,${this.getSubTypeName(subType)}]${animalNames.join(',')}`;
                
                // 如果组合太长，显示省略形式
                if (animalNames.length > 3) {
                    description = `[生肖,${this.getSubTypeName(subType)}]${animalNames.slice(0, 3).join(',')}...详细`;
                }
                
                const betItem = {
                    id: CommonUtils.generateId(),
                    type: 'animal',
                    game: STATE.currentGame,
                    sub: STATE.currentSub,
                    animals: selectedAnimals,
                    count: 1,
                    amount: 10,
                    odds: initialOdds,
                    gameTypeKey: gameTypeKey,
                    description: description,
                    isReverse: subType === 'hexiaobuzhong' // 标记是否为反向投注
                };
                
                StateManager.addBetItem(betItem);
                break;
        }
    },

    // 生成生肖组合
    generateAnimalCombinations(selectedAnimals, size, subType, gameTypeKey, lastUsedOdds) {
        const combinations = CommonUtils.generateCombinations(selectedAnimals, size);
        const hasBenming = selectedAnimals.some(id => animalConfig.getAnimalById(id).isBenming);
        const odds = this.getAnimalCombinationOdds(subType, hasBenming);
        const initialOdds = lastUsedOdds || odds;
        
        combinations.forEach(combination => {
            const animalNames = combination.map(id => animalConfig.getAnimalById(id).name);
            const betItem = {
                id: CommonUtils.generateId(),
                type: 'animal',
                game: STATE.currentGame,
                sub: STATE.currentSub,
                animals: combination,
                count: 1,
                amount: 10,
                odds: initialOdds,
                gameTypeKey: gameTypeKey,
                description: `[生肖,${this.getSubTypeName(subType)}]${animalNames.join(',')}`
            };
            
            StateManager.addBetItem(betItem);
        });
    },

    // 获取生肖赔率
    getAnimalOdds(animal, subType) {
        const config = oddsConfig.shengxiao[subType];
        if (!config) return 1;
        
        return animal.isBenming ? config.benming : config.normal;
    },

    // 获取生肖组合赔率
    getAnimalCombinationOdds(subType, hasBenming) {
        const config = oddsConfig.shengxiao[subType];
        if (!config) return 1;
        
        return hasBenming ? config.withBenming : config.withoutBenming;
    },

    // 获取子玩法名称
    getSubTypeName(subType) {
        const names = {
            'texiao': '特肖',
            'yixiao': '一肖',
            'erxiaolian': '二肖连',
            'sanxiaolian': '三肖连',
            'sixiaolian': '四肖连',
            'zongxiao': '总肖',
            'zhengxiao': '正肖',
            'hexiaozhong': '合肖中',
            'hexiaobuzhong': '合肖不中'
        };
        return names[subType] || subType;
    },

    // 处理尾数点击
    handleTailClick(button) {
        const tail = button.getAttribute('data-tail');
        const tailType = button.getAttribute('data-tail-type'); // 'head' 或 'tail' 或 null
        const isSelected = button.classList.contains('selected');
        
        if (isSelected) {
            // 取消选择
            button.classList.remove('selected');
            if (tailType === 'head') {
                StateManager.removeSelectedHead(tail);
            } else {
                StateManager.removeSelectedTail(tail);
            }
        } else {
            // 检查选择限制
            if (!this.checkTailSelectionLimit(tail, tailType)) {
                return;
            }
            
            // 选择尾数
            button.classList.add('selected');
            if (tailType === 'head') {
                StateManager.addSelectedHead(tail);
            } else {
                StateManager.addSelectedTail(tail);
            }
        }
        
        this.updateTailSelectionInfo();
    },

    // 检查尾数选择限制
    checkTailSelectionLimit(tail, tailType) {
        const subType = STATE.currentSub;
        
        if (subType === 'tematowei') {
            // 特码头尾：头数和尾数可以分别选择多个，每个独立投注
            if (tailType === 'head') {
                if (STATE.selectedHeads.size >= 5) {
                    alert('特码头尾：头数最多选择5个');
                    return false;
                }
            } else {
                if (STATE.selectedTails.size >= 10) {
                    alert('特码头尾：尾数最多选择10个');
                    return false;
                }
            }
        } else if (subType === 'erweilian') {
            // 二尾连：可以选择2个或更多尾数，生成所有二尾连组合
            if (STATE.selectedTails.size >= 10) {
                alert('二尾连最多选择10个尾数');
                return false;
            }
        } else if (subType === 'sanweilian') {
            // 三尾连：可以选择3个或更多尾数，生成所有三尾连组合
            if (STATE.selectedTails.size >= 10) {
                alert('三尾连最多选择10个尾数');
                return false;
            }
        } else if (subType === 'siweilian') {
            // 四尾连：可以选择4个或更多尾数，生成所有四尾连组合
            if (STATE.selectedTails.size >= 10) {
                alert('四尾连最多选择10个尾数');
                return false;
            }
        } else if (subType === 'zhengteweishu') {
            // 正特尾数可以选择多个
            if (STATE.selectedTails.size >= 10) {
                alert('正特尾数最多选择10个尾数');
                return false;
            }
        }
        
        return true;
    },

    // 更新尾数选择信息
    updateTailSelectionInfo() {
        const subType = STATE.currentSub;
        let count = 0;
        let selectionText = '';
        
        if (subType === 'tematowei') {
            // 特码头尾：头数和尾数分别计算注数
            const headCount = STATE.selectedHeads.size;
            const tailCount = STATE.selectedTails.size;
            count = headCount + tailCount; // 头数注数 + 尾数注数
            
            const parts = [];
            if (headCount > 0) {
                const selectedHeads = Array.from(STATE.selectedHeads);
                parts.push(`头数${headCount}注(${selectedHeads.join(',')})`);
            }
            if (tailCount > 0) {
                const selectedTails = Array.from(STATE.selectedTails);
                parts.push(`尾数${tailCount}注(${selectedTails.join(',')})`);
            }
            selectionText = parts.join(' ');
        } else {
            // 其他尾数玩法
            const selectedTails = Array.from(STATE.selectedTails);
            count = this.calculateTailCombinationCount(selectedTails, subType);
            
            if (selectedTails.length > 0) {
                selectionText = `已选尾数：${selectedTails.join(',')}`;
            }
        }
        
        const selectionCountElement = document.getElementById(`${STATE.currentSub}SelectionCount`);
        const confirmBtn = document.getElementById(`${STATE.currentSub}ConfirmBtn`);
        
        if (selectionCountElement) {
            if (count > 0) {
                selectionCountElement.textContent = `您选择了 ${count} 注 - ${selectionText}`;
            } else {
                selectionCountElement.textContent = `您选择了 0 注`;
            }
        }
        
        if (confirmBtn) {
            confirmBtn.disabled = count === 0;
        }
    },

    // 计算尾数组合注数
    calculateTailCombinationCount(tails, subType) {
        if (tails.length === 0) return 0;
        
        switch (subType) {
            case 'erweilian':
                return tails.length >= 2 ? TailUtils.generateCombinations(tails, 2).length : 0;
            case 'sanweilian':
                return tails.length >= 3 ? TailUtils.generateCombinations(tails, 3).length : 0;
            case 'siweilian':
                return tails.length >= 4 ? TailUtils.generateCombinations(tails, 4).length : 0;
            case 'zhengteweishu':
                return tails.length; // 每个尾数一注
            default:
                return 0;
        }
    },

    // 确认尾数选择
    confirmTailSelection() {
        const subType = STATE.currentSub;
        
        if (subType === 'tematowei') {
            const selectedHeads = Array.from(STATE.selectedHeads);
            const selectedTails = Array.from(STATE.selectedTails);
            
            if (!this.validateTailSelection(selectedHeads, selectedTails, subType)) {
                return;
            }
            
            this.generateTailBetItems(selectedHeads, selectedTails, subType);
        } else {
            const selectedTails = Array.from(STATE.selectedTails);
            
            if (!this.validateTailSelection(selectedTails, [], subType)) {
                return;
            }
            
            this.generateTailBetItems(selectedTails, [], subType);
        }
        
        // 清空选择并更新显示
        this.clearTailSelection();
        this.updateBettingListDisplay();
    },

    // 验证尾数选择
    validateTailSelection(selectedTails, selectedHeads, subType) {
        if (subType === 'tematowei') {
            if (selectedHeads.length === 0 && selectedTails.length === 0) {
                alert('特码头尾需要选择头数或尾数');
                return false;
            }
        } else {
            if (selectedTails.length === 0) {
                alert('请选择尾数');
                return false;
            }
            
            const minRequired = {
                'erweilian': 2,
                'sanweilian': 3,
                'siweilian': 4,
                'zhengteweishu': 1
            };
            
            if (selectedTails.length < minRequired[subType]) {
                alert(`${this.getTailSubTypeName(subType)}至少需要选择${minRequired[subType]}个尾数`);
                return false;
            }
        }
        
        return true;
    },

    // 生成尾数投注项
    generateTailBetItems(selectedTails, selectedHeads, subType) {
        const gameTypeKey = `weishu_${subType}`;
        const lastUsedOdds = StateManager.getLastUsedOdds(gameTypeKey);
        
        if (subType === 'tematowei') {
            // 特码头尾：头数和尾数分别投注
            // 生成头数投注项
            for (const head of selectedHeads) {
                const headOdds = oddsConfig.weishu.tematowei.head[head];
                const headBetItem = {
                    id: CommonUtils.generateId(),
                    type: 'tail',
                    game: STATE.currentGame,
                    sub: STATE.currentSub,
                    tailType: 'head',
                    tails: [head],
                    count: 1,
                    amount: 10,
                    odds: lastUsedOdds || headOdds,
                    gameTypeKey: `${gameTypeKey}_head`,
                    description: `[尾数,特码头尾]头${head}`
                };
                StateManager.addBetItem(headBetItem);
            }
            
            // 生成尾数投注项
            for (const tail of selectedTails) {
                const tailOdds = oddsConfig.weishu.tematowei.tail[tail];
                const tailBetItem = {
                    id: CommonUtils.generateId(),
                    type: 'tail',
                    game: STATE.currentGame,
                    sub: STATE.currentSub,
                    tailType: 'tail',
                    tails: [tail],
                    count: 1,
                    amount: 10,
                    odds: lastUsedOdds || tailOdds,
                    gameTypeKey: `${gameTypeKey}_tail`,
                    description: `[尾数,特码头尾]尾${tail}`
                };
                StateManager.addBetItem(tailBetItem);
            }
        } else {
            // 其他尾数玩法
            const combinations = this.generateTailCombinations(selectedTails, subType, gameTypeKey, lastUsedOdds);
            
            for (const combination of combinations) {
                StateManager.addBetItem(combination);
            }
        }
    },

    // 生成尾数组合
    generateTailCombinations(selectedTails, subType, gameTypeKey, lastUsedOdds) {
        const combinations = [];
        const subTypeName = this.getTailSubTypeName(subType);
        
        if (subType === 'zhengteweishu') {
            // 正特尾数：按含0尾和不含0尾分组
            const withZeroTails = selectedTails.filter(tail => tail === '0');
            const withoutZeroTails = selectedTails.filter(tail => tail !== '0');
            
            // 生成含0尾的投注项
            if (withZeroTails.length > 0) {
                combinations.push({
                    id: CommonUtils.generateId(),
                    type: 'tail',
                    game: STATE.currentGame,
                    sub: STATE.currentSub,
                    tails: withZeroTails,
                    count: withZeroTails.length,
                    amount: 10,
                    odds: lastUsedOdds || oddsConfig.weishu.zhengteweishu.withZero,
                    gameTypeKey: `${gameTypeKey}_withZero`,
                    description: `[尾数,${subTypeName}]${withZeroTails.join(',')}尾(含0尾)`
                });
            }
            
            // 生成不含0尾的投注项
            if (withoutZeroTails.length > 0) {
                combinations.push({
                    id: CommonUtils.generateId(),
                    type: 'tail',
                    game: STATE.currentGame,
                    sub: STATE.currentSub,
                    tails: withoutZeroTails,
                    count: withoutZeroTails.length,
                    amount: 10,
                    odds: lastUsedOdds || oddsConfig.weishu.zhengteweishu.withoutZero,
                    gameTypeKey: `${gameTypeKey}_withoutZero`,
                    description: `[尾数,${subTypeName}]${withoutZeroTails.join(',')}尾(不含0尾)`
                });
            }
        } else if (subType === 'erweilian') {
            // 二尾连：合并投注，按含0尾和不含0尾分组
            const size = 2;
            const tailCombinations = TailUtils.generateCombinations(selectedTails, size);
            
            // 分组：含0尾和不含0尾
            const withZeroCombs = tailCombinations.filter(comb => comb.includes('0'));
            const withoutZeroCombs = tailCombinations.filter(comb => !comb.includes('0'));
            
            // 生成含0尾的合并投注项
            if (withZeroCombs.length > 0) {
                combinations.push({
                    id: CommonUtils.generateId(),
                    type: 'tail',
                    game: STATE.currentGame,
                    sub: STATE.currentSub,
                    tails: selectedTails, // 保存原始选择的尾数
                    tailCombinations: withZeroCombs, // 保存具体的组合
                    count: withZeroCombs.length,
                    amount: 10,
                    odds: lastUsedOdds || oddsConfig.weishu.erweilian.withZero,
                    gameTypeKey: `${gameTypeKey}_withZero`,
                    description: `[尾数,${subTypeName}]${selectedTails.join(',')}尾(含0尾)`
                });
            }
            
            // 生成不含0尾的合并投注项
            if (withoutZeroCombs.length > 0) {
                combinations.push({
                    id: CommonUtils.generateId(),
                    type: 'tail',
                    game: STATE.currentGame,
                    sub: STATE.currentSub,
                    tails: selectedTails, // 保存原始选择的尾数
                    tailCombinations: withoutZeroCombs, // 保存具体的组合
                    count: withoutZeroCombs.length,
                    amount: 10,
                    odds: lastUsedOdds || oddsConfig.weishu.erweilian.withoutZero,
                    gameTypeKey: `${gameTypeKey}_withoutZero`,
                    description: `[尾数,${subTypeName}]${selectedTails.join(',')}尾(不含0尾)`
                });
            }
        } else if (subType === 'sanweilian') {
            // 三尾连：合并投注，按含0尾和不含0尾分组
            const size = 3;
            const tailCombinations = TailUtils.generateCombinations(selectedTails, size);
            
            // 分组：含0尾和不含0尾
            const withZeroCombs = tailCombinations.filter(comb => comb.includes('0'));
            const withoutZeroCombs = tailCombinations.filter(comb => !comb.includes('0'));
            
            // 生成含0尾的合并投注项
            if (withZeroCombs.length > 0) {
                combinations.push({
                    id: CommonUtils.generateId(),
                    type: 'tail',
                    game: STATE.currentGame,
                    sub: STATE.currentSub,
                    tails: selectedTails, // 保存原始选择的尾数
                    tailCombinations: withZeroCombs, // 保存具体的组合
                    count: withZeroCombs.length,
                    amount: 10,
                    odds: lastUsedOdds || oddsConfig.weishu.sanweilian.withZero,
                    gameTypeKey: `${gameTypeKey}_withZero`,
                    description: `[尾数,${subTypeName}]${selectedTails.join(',')}尾(含0尾)`
                });
            }
            
            // 生成不含0尾的合并投注项
            if (withoutZeroCombs.length > 0) {
                combinations.push({
                    id: CommonUtils.generateId(),
                    type: 'tail',
                    game: STATE.currentGame,
                    sub: STATE.currentSub,
                    tails: selectedTails, // 保存原始选择的尾数
                    tailCombinations: withoutZeroCombs, // 保存具体的组合
                    count: withoutZeroCombs.length,
                    amount: 10,
                    odds: lastUsedOdds || oddsConfig.weishu.sanweilian.withoutZero,
                    gameTypeKey: `${gameTypeKey}_withoutZero`,
                    description: `[尾数,${subTypeName}]${selectedTails.join(',')}尾(不含0尾)`
                });
            }
        } else if (subType === 'siweilian') {
            // 四尾连：合并投注，按含0尾和不含0尾分组
            const size = 4;
            const tailCombinations = TailUtils.generateCombinations(selectedTails, size);
            
            // 分组：含0尾和不含0尾
            const withZeroCombs = tailCombinations.filter(comb => comb.includes('0'));
            const withoutZeroCombs = tailCombinations.filter(comb => !comb.includes('0'));
            
            // 生成含0尾的合并投注项
            if (withZeroCombs.length > 0) {
                combinations.push({
                    id: CommonUtils.generateId(),
                    type: 'tail',
                    game: STATE.currentGame,
                    sub: STATE.currentSub,
                    tails: selectedTails, // 保存原始选择的尾数
                    tailCombinations: withZeroCombs, // 保存具体的组合
                    count: withZeroCombs.length,
                    amount: 10,
                    odds: lastUsedOdds || oddsConfig.weishu.siweilian.withZero,
                    gameTypeKey: `${gameTypeKey}_withZero`,
                    description: `[尾数,${subTypeName}]${selectedTails.join(',')}尾(含0尾)`
                });
            }
            
            // 生成不含0尾的合并投注项
            if (withoutZeroCombs.length > 0) {
                combinations.push({
                    id: CommonUtils.generateId(),
                    type: 'tail',
                    game: STATE.currentGame,
                    sub: STATE.currentSub,
                    tails: selectedTails, // 保存原始选择的尾数
                    tailCombinations: withoutZeroCombs, // 保存具体的组合
                    count: withoutZeroCombs.length,
                    amount: 10,
                    odds: lastUsedOdds || oddsConfig.weishu.siweilian.withoutZero,
                    gameTypeKey: `${gameTypeKey}_withoutZero`,
                    description: `[尾数,${subTypeName}]${selectedTails.join(',')}尾(不含0尾)`
                });
            }
        }
        
        return combinations;
    },

    // 清空尾数选择
    clearTailSelection() {
        StateManager.clearSelectedTails();
        StateManager.clearSelectedHeads();
        
        // 清除按钮选中状态
        document.querySelectorAll('.tail-btn.selected').forEach(btn => {
            btn.classList.remove('selected');
        });
        
        this.updateTailSelectionInfo();
    },

    // 获取尾数子玩法名称
    getTailSubTypeName(subType) {
        const nameMap = {
            'tematowei': '特码头尾',
            'erweilian': '二尾连',
            'sanweilian': '三尾连',
            'siweilian': '四尾连',
            'zhengteweishu': '正特尾数'
        };
        return nameMap[subType] || subType;
    },

    // 确认不中选号
    confirmBuzhongSelection() {
        const selectedNumbers = Array.from(STATE.selectedNumbers);
        const subType = STATE.currentSub;
        
        if (!this.validateBuzhongSelection(selectedNumbers, subType)) {
            return;
        }
        
        // 生成投注项目
        this.generateBuzhongBetItems(selectedNumbers, subType);
        
        // 清空选择
        this.clearNumberSelection();
        
        // 更新投注清单显示
        this.updateBettingListDisplay();
    },

    // 验证不中选择
    validateBuzhongSelection(selectedNumbers, subType) {
        const count = selectedNumbers.length;
        const minRequiredMap = {
            'wubuzhong': 5,
            'liubuzhong': 6,
            'qibuzhong': 7,
            'babuzhong': 8,
            'jiubuzhong': 9,
            'shibuzhong': 10
        };
        
        const minRequired = minRequiredMap[subType];
        if (count < minRequired) {
            alert(`${this.getBuzhongSubTypeName(subType)}至少需要选择${minRequired}个号码`);
            return false;
        }
        
        return true;
    },

    // 生成不中投注项目
    generateBuzhongBetItems(selectedNumbers, subType) {
        const gameTypeKey = CommonUtils.getGameTypeKey(STATE.currentGame, STATE.currentSub);
        const lastUsedOdds = StateManager.getLastUsedOdds(gameTypeKey);
        
        // 获取对应的注数（组合数）
        const count = this.calculateBuzhongCombinationCount(selectedNumbers, subType);
        const odds = lastUsedOdds || oddsConfig.buzhong[subType];
        const subTypeName = this.getBuzhongSubTypeName(subType);
        
        // 生成投注项描述
        let description = `[不中,${subTypeName}]${selectedNumbers.join(',')}`;
        if (selectedNumbers.length > 5) {
            description = `[不中,${subTypeName}]${selectedNumbers.slice(0, 5).join(',')}...详细`;
        }
        
        const betItem = {
            id: CommonUtils.generateId(),
            type: 'buzhong',
            game: STATE.currentGame,
            sub: STATE.currentSub,
            numbers: selectedNumbers,
            count: count,
            amount: 10,
            odds: odds,
            gameTypeKey: gameTypeKey,
            description: description
        };
        
        StateManager.addBetItem(betItem);
    },

    // 计算不中组合注数
    calculateBuzhongCombinationCount(selectedNumbers, subType) {
        const count = selectedNumbers.length;
        const combinationSizeMap = {
            'wubuzhong': 5,
            'liubuzhong': 6,
            'qibuzhong': 7,
            'babuzhong': 8,
            'jiubuzhong': 9,
            'shibuzhong': 10
        };
        
        const combinationSize = combinationSizeMap[subType];
        if (count < combinationSize) return 0;
        
        return CommonUtils.calculateCombination(count, combinationSize);
    },

    // 获取不中子玩法名称
    getBuzhongSubTypeName(subType) {
        const nameMap = {
            'wubuzhong': '五不中',
            'liubuzhong': '六不中',
            'qibuzhong': '七不中',
            'babuzhong': '八不中',
            'jiubuzhong': '九不中',
            'shibuzhong': '十不中'
        };
        return nameMap[subType] || subType;
    },

    // 处理色波按钮点击
    handleSeboButtonClick(button) {
        const seboType = button.getAttribute('data-sebo');
        const odds = parseFloat(button.getAttribute('data-odds'));
        const isSelected = button.classList.contains('selected');
        
        // 获取按钮文本（去掉赔率部分）
        const buttonText = button.textContent.split('\n')[0] || button.textContent.split('赔率')[0];
        const betName = buttonText.trim();
        
        const description = `[色波,七色波]${betName}`;
        
        if (isSelected) {
            // 取消选中状态
            button.classList.remove('selected');
            
            // 从投注清单中移除对应项目
            STATE.betList = STATE.betList.filter(bet => {
                return !(bet.type === 'sebo' && 
                        bet.game === STATE.currentGame && 
                        bet.sub === STATE.currentSub && 
                        bet.sebo === seboType);
            });
        } else {
            // 设置选中状态
            button.classList.add('selected');
            
            // 获取玩法标识
            const gameTypeKey = `sebo_${seboType}`;
            
            // 优先使用历史赔率，否则使用按钮上的赔率
            const lastUsedOdds = StateManager.getLastUsedOdds(gameTypeKey);
            const initialOdds = lastUsedOdds || odds;
            
            // 添加到投注清单
            const betItem = {
                id: CommonUtils.generateId(),
                type: 'sebo',
                game: STATE.currentGame,
                sub: STATE.currentSub,
                sebo: seboType,
                count: 1,
                amount: 10,
                odds: initialOdds,
                gameTypeKey: gameTypeKey,
                description: description
            };
            
            StateManager.addBetItem(betItem);
        }
        
        // 更新投注清单显示
        this.updateBettingListDisplay();
        
        // 更新选择信息
        this.updateSeboSelectionInfo();
        
        // 添加视觉反馈
        button.style.transform = 'scale(0.95)';
        setTimeout(() => {
            button.style.transform = 'scale(1)';
        }, 150);
    },

    // 更新色波选择信息
    updateSeboSelectionInfo() {
        const selectedButtons = document.querySelectorAll('.sebo-btn.selected');
        const count = selectedButtons.length;
        
        const selectionCount = document.getElementById('qiseboSelectionCount');
        const confirmBtn = document.getElementById('qiseboConfirmBtn');
        
        if (selectionCount) {
            selectionCount.textContent = `您选择了 ${count} 注`;
        }
        
        if (confirmBtn) {
            confirmBtn.disabled = count === 0;
        }
    },

    // 确认色波选择
    confirmSeboSelection() {
        const selectedButtons = document.querySelectorAll('.sebo-btn.selected');
        if (selectedButtons.length === 0) return;
        
        // 色波按钮点击时已经添加到投注清单，这里只需要更新选择信息
        this.updateSeboSelectionInfo();
    }
};